package top.ajun.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import top.ajun.common.utils.CodeEnum;
import top.ajun.common.utils.R;

import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理器
 *
 * @author AJun
 * @date 2020/12/1
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(ApiException.class)
    public R handleRRException(ApiException e) {
        log.error(e.getMessage(), e);
        return R.error(e.getCode(), e.getMessage());
    }

    /**
     * 数据校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现异常{}, 异常类型{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            // 错误提示
            String errorMsg = item.getDefaultMessage();
            // 发生错误的属性名称
            String field = item.getField();
            errorMap.put(field, errorMsg);
        });
        return R.error(CodeEnum.VALID_EXCEPTION.getCode(), errorMap, CodeEnum.VALID_EXCEPTION.getMsg());
    }

    @ExceptionHandler(value = BindException.class)
    public R handleValidException(BindException e) {
        log.error("数据校验出现异常{}, 异常类型{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            // 错误提示
            String errorMsg = item.getDefaultMessage();
            // 发生错误的属性名称
            String field = item.getField();
            errorMap.put(field, errorMsg);
        });
        return R.error(CodeEnum.VALID_EXCEPTION.getCode(), errorMap, CodeEnum.VALID_EXCEPTION.getMsg());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error(CodeEnum.NOT_FOUND.getCode(), "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public R handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return R.error("数据库中已存在该记录");
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(e.getMessage(), e);
        return R.error();
    }

}
